#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# xhs_search_dropdown.py

"""
搜索下拉词爬虫
使用Playwright自动获取搜索引擎的下拉搜索建议
"""

import os
import sys

# 添加项目根目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(current_dir))

# 初始化playwright配置
from playwright.sync_api import sync_playwright
from src.element_locator_item import search_input_box, search_dropdown_word, search_box_icon
from config import AUTH_FILE, Config

# 设置search_keyword和search_keyword_list
search_keyword_dict = {}

def main(search_keyword="2333"):
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=Config.IF_HEADLESS)

        context = browser.new_context(storage_state=AUTH_FILE if os.path.exists(AUTH_FILE) else None)  
        page = context.new_page()
        
        # 跳转到小红书页面
        page.goto("https://www.xiaohongshu.com/")
        
        # 定位并点击搜索框
        search_input = page.locator(search_input_box.get('element_locator'))
        search_input.click()
        
        # 清空搜索框并输入关键词
        search_input.fill("")
        page.wait_for_timeout(500)
        search_input.fill(search_keyword)
        
        # 等待下拉框出现
        page.wait_for_selector(search_dropdown_word.get('element_locator'), state='visible')
        page.wait_for_timeout(2000)
        
        # 使用JavaScript获取搜索建议
        search_results = page.evaluate("""
            () => {
                return new Promise((resolve) => {
                    // 给一点时间让下拉列表完全加载
                    setTimeout(() => {
                        const elements = document.querySelectorAll('%s');
                        const results = Array.from(elements)
                            .map(el => el.textContent.trim())
                            .filter(text => text !== '');
                        resolve(results);
                    }, 1000);
                });
            }
        """ % search_dropdown_word.get('element_locator'))
        
        search_keyword_dict['search_dropdown_words'] = search_results
        #print(search_keyword_dict)
        # 保存登录状态
        context.storage_state(path=AUTH_FILE)
        browser.close()
    return search_keyword_dict

if __name__ == "__main__":
    main()